/*
 * @Author: wuqingchun
 * @Date: 2024-07-23 17:23:36
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-07-24 11:30:20
 */

#include <algorithm>

#include "common.h"
#include "thread_cache.h"
#include "central_cache.h"


void* ThreadCache::Alloc(size_t ulSize)
{
    size_t ulIndex = SizeAlignStrategy::Index(ulSize);
    size_t ulAlignSize = SizeAlignStrategy::AlignSize(ulSize);
    
    if (m_arrFreeList[ulIndex].Empty())
    {
        return __AllocFromCCache(ulIndex, ulAlignSize);
    }

    return m_arrFreeList[ulIndex].Pop();
}

void ThreadCache::Free(void* pMem)
{

}

void* ThreadCache::__AllocFromCCache(size_t ulIndex, size_t ulSize)
{
    // 慢开始反馈调节算法
    //NumMoveSize决定上限
    size_t ulObjNum = std::min(m_arrFreeList[ulIndex].GetExpandNum(), SizeAlignStrategy::NumMoveSize(ulSize));
    if (ulObjNum == m_arrFreeList[ulIndex].GetExpandNum())
    {
        m_arrFreeList[ulIndex].IncrExpandNum();
    }

    // 从中心缓存中获取一段内存 可能会多申请 多申请的放到thread cache即可
    void* pStart = nullptr;
    void* pEnd = nullptr;
    ulObjNum = CentralCache::GetInstance()->FetchRangeObj(pStart, pEnd, ulObjNum, ulSize);
    if (ulObjNum == 0)
    {
        return nullptr;
    }
    
    if (ulObjNum > 1)
    {
        // 多申请的对象放入对应的 free list
        m_arrFreeList[ulIndex].BatchPush(FreeList::GetNextObject(pStart), pEnd, ulObjNum - 1);
        return pStart;
    }

    return pStart;
}